import jdk.internal.org.objectweb.asm.tree.MethodInsnNode;

import javax.print.attribute.EnumSyntax;
import java.util.Arrays;
import java.util.EnumSet;

/**
 * @author ZCR
 * @create 2025/9/2 23:25
 */
public class Solution1011 {
    public int shipWithinDays(int[] weights, int days) {
        int sum = 0;
        int min = 0;
        for (int i = 0; i < weights.length; i++) {
            min = Math.max(min, weights[i]);
            sum += weights[i];
        }
        int max = sum;
        return lower(weights, min, max, days);
    }

    public int lower(int[] nums, int left, int right, int days) {
        //为啥 left <=right right =mid-1
        //left<right right=mid
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (f1(nums, mid) <= days) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    public int f1(int[] nums, int target) {
        int count = 0;
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if (sum + nums[i] <= target) {
                sum += nums[i];
            } else {
                count++;
                sum = nums[i];
            }
        }
        if (sum <= target) {
            count++;
        }
        return count;
    }

    public int f2(int[] nums, int target) {
        int count = 0;
        for (int i = 0; i < nums.length; ) {
            int cap = target;
            while (i < nums.length) {
                if (cap < nums[i]) break;
                else cap -= nums[i];
                i++;
            }
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        Solution1011 solution = new Solution1011();
        System.out.println(solution.shipWithinDays(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5));
        System.out.println(solution.shipWithinDays(new int[]{3, 2, 2, 4, 1, 4}, 3));
        System.out.println(solution.shipWithinDays(new int[]{1, 2, 3, 1, 1}, 4));
    }
}
